﻿using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using UIWindow.Attributes;
using UIWindow.Commands;
using UIWindow.Domains;
using UIWindow.GlobalParameters;
using UIWindow.Helper;
using UIWindow.Services;
using UIWindow.ViewModels.Dialogs;
using UIWindow.Views.Dialogs;

namespace UIWindow.ViewModels
{
    public class MainWindowViewModel
    {
        private bool _isrun;
        public MainGlobal MyMain { get; set; }
        public ParameterGlobal MyParameter { get; set; }
        private TaskService _taskService;
        private HomePageGlobal _pageGlobal;

        public MainWindowViewModel()
        {
            MyMain = Bootstrapper.GetContainer().ResolveSingleton<MainGlobal>();
            MyParameter = Bootstrapper.GetContainer().ResolveSingleton<ParameterGlobal>();
            _pageGlobal = Bootstrapper.GetContainer().ResolveSingleton<HomePageGlobal>();
            _taskService = new TaskService(MyParameter, 
                Bootstrapper.GetContainer().ResolveSingleton<DeviceGlobal>(), 
                MyMain, _pageGlobal, 
                Bootstrapper.GetContainer().ResolveSingleton<UserGlobal>());
            if (GlobalStart.IsDeBug) MyMain.UpdateMenu();
            _isrun = false;
            LogMessage.RunLog("初始化完成", Enums.MessageLevelType.Info);
        }

        public DelegateCommand HelperButton => new DelegateCommand(() => _ = DialogHost.Show(new HelperDialogs(), "RootDialog").ConfigureAwait(false));

        public DelegateCommand ExitLogin => new DelegateCommand(() =>
        {
            if (_isrun)
            {
                "设备运行中，请勿退出！！！".MessageDialogs(Enums.MessageLevelType.Warning);
                return;
            }
            DialogHost.Show(new LoginDialogs() { DataContext = new LoginDialogsViewModel() }, "RootDialog").ConfigureAwait(false);
        });

        /// <summary>
        /// 执行任务
        /// </summary>
        public DelegateCommand<Button> PerformTask => new DelegateCommand<Button>(async sender =>
        {
            _ = DialogHost.Show(new LoadingDialogs(), "RootDialog").ConfigureAwait(false);
            if (sender.Content.ToString() == "    运  行    ")
            {
                if (!await _taskService.SwitchOn())
                {
                    "任务启动失败！\r\n请检查网络连接后再次启动...".MessageDialogs(Enums.MessageLevelType.Error);
                    return;
                }
                sender.Content = "    停  止    ";
                _isrun = true;
            }
            else
            {
                _taskService.Stop();
                _isrun = false;
                sender.Content = "    运  行    ";
            }
            if (DialogHost.IsDialogOpen("RootDialog")) DialogHost.Close("RootDialog");
        });
    }
}
